<style scoped>
    .config_main {
        padding: 20px;
        background: #fff;
    }
    .bottom .top{
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
    }
    .btns{
        width:60%;
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        margin-top:30px;
        align-items: center;
        justify-content: flex-start;
    }
    .comm_build_textarea {
        width: 840px;
        height: 220px;
    }
    .com_model_block .left{
        width:130px;
    }
</style>
<div class="content" id="team" v-cloak>
    <el-row>
        <el-col :span="12">
            <div class="grid-content bg-purple com_title">资产脚本任务</div>
        </el-col>
    </el-row>
    <div class="config_main mt30">
        <div class="bottom">
            <div class="top mb20">
                <div>资产列表</div> 
                <el-button @click="addNewCommTask" type="primary" icon="el-icon-plus" size="small">新建脚本任务</el-button>
            </div>
            <div class="mb20">
                <span class="ml10 light">
                    <i class="el-icon-warning fs-16 mr5 primary"></i>
                    资产脚本任务可进行各种应用的安装，各种应用的版本检测，支持各种脚本命令，支持单机和多机运行。
                </span>
            </div>
            <el-table 
                :data="assetslist" border 
                ref="multipleTable"
                @selection-change="handleSelectionChange"
                style="width:100%;font-size:13px;">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="name" label="资产名称">
                </el-table-column>
                <el-table-column prop="code" label="资产编码">
                </el-table-column>
                <el-table-column prop="outer_ip" label="外网IP">
                </el-table-column>
                <el-table-column prop="lan_ip" label="内网IP">
                </el-table-column>
                <el-table-column prop="user" label="用户名" width="120">
                </el-table-column>
                <el-table-column label="操作"  width="500" fixed="right">
                    <template slot-scope="scope" >
                        <div>
                            <span v-for="(item,index) in tasklist" :key="index">
                                <el-button 
                                    @click="showTaskOpctions(2,item,scope.row)"
                                    v-if="item.type==1?true:false" 
                                    :type="item.btn_color" 
                                    :plain="item.is_plain==1?true:false"
                                    size="mini" 
                                    >{{item.name}}</el-button>
                                    <div v-if="index!==0 && index%3===0" class="mb10"></div>
                            </span>
                            <el-button @click="showSshKey(scope.row)" type="danger" size="mini">获得SSH KEY</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="btns">
            <span 
                v-for="(item,index) in tasklist" 
                :key="index" 
                v-if="item.type==2?true:false" 
                class="ml10" >
                <el-button 
                    @click="showTaskOpctions(1,item)"
                    :type="item.btn_color" 
                    :plain="item.is_plain==1?true:false"
                    size="medium">{{item.name}}</el-button>
            </span>
        </div>
        <!-- ssk 弹出框 -->
        <el-dialog width="800px" title="SSH KEY" :visible.sync="sshkey.dialogSshKeyVisible">
            <div class="com_model_main">
                <div class="mb20 common_tops"><i class="el-icon-warning"></i>请尽量使用获得ssh key按钮，若生成新的ssh key则相关地方均需要更改（例如：github
                    ssk）</div>
                <div>
                    <el-button @click="getSshKey(1)" type="primary" plain>获得SSH KEY</el-button>
                </div>
                <div class="block mt30">
                    <div class="left" style="width:80px;">邮箱地址</div>
                    <div class="right">
                        <el-input v-model="sshkey.email" style="width:200px;margin-right:15px;" placeholder="用来生成ssh key的邮箱备注">
                        </el-input>
                        <el-button @click="getSshKey(2)" class="ml10" type="danger" plain>生成新的SSH KEY</el-button>
                    </div>
                </div>
                <div class="mt30 mb20">ssh key</div>
                <el-input type="textarea" :rows="6" v-model="sshkey.sshKey"></el-input>
            </div>
        </el-dialog>

        <!-- model弹出框 -->
        <el-dialog width="1000px" title="运行脚本任务" :visible.sync="dialogTableVisible">
            <div class="com_model_main">
                <el-row>
                    <el-col :span="12">
                        <div class="com_model_block">
                            <div class="left">任务名称：</div>
                            <div>{{taskItem.name}}</div>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="com_model_block">
                            <div class="left">任务类型：</div>
                            <div>{{taskItem.type==1?'窗口运行命令':''}}{{taskItem.type==2?'shell脚本命令':''}}</div>
                        </div>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <div class="com_model_block" v-if="taskItem.type==2?true:false">
                            <div class="left">shell脚本路径：</div>
                            <div>{{taskItem.shell_path}}</div>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="com_model_block" v-if="taskItem.type==2?true:false">
                            <div class="left">shell脚本参数：</div>
                            <div>{{taskItem.shell_opction}}</div>
                        </div>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <div class="com_model_block" v-if="taskItem.type==2?true:false">
                            <div class="left">shell脚本写入方式：</div>
                            <div>{{taskItem.shell_write_type==1?'新建文件并上传方式':''}}{{taskItem.shell_write_type==2?'shell窗口命令行创建方式':''}}</div>
                        </div>
                    </el-col>
                </el-row>
                <div class="com_model_block">
                    <div class="left">任务脚本内容：</div>
                    <div id="editor" class="comm_build_textarea"></div>
                </div>
                <div class="ml10 light tc" v-if="taskItem.type==2?true:false">
                    <i class="el-icon-warning fs-16 mr5 primary"></i>
                    请确保已生成构建配置，若未生成构建配置，则先执行生成配置按钮，再执行任务。
                </div>
                <div class="btns">
                    <el-button type="primary" @click="deployApplications">执行任务</el-button>
                    <el-button type="danger" v-if="taskItem.type==2?true:false" @click="generateBuildConfig" plain>生成配置</el-button>
                    <el-button type="success" @click="updageAppConfigs" plain>修改配置</el-button>
                </div>
            </div>
        </el-dialog>

        <!-- xtrem弹出框 -->
        <div class="comm_shell_model" v-show="dialogBuildVisible">
            <div class="mask" @click="dialogBuildVisible=false"></div>
            <div class="comm_shell_model_content">
                <span class="el-icon-close close" @click="dialogBuildVisible=false"></span>
                <span :class="{'el-icon-menu':model_icon===1,'el-icon-s-unfold':model_icon===2}" class="close menu"
                    @click="handleShellModel(3)"></span>
                <span class="el-icon-plus close plus" @click="handleShellModel(1)"></span>
                <span class="el-icon-minus close minus" @click="handleShellModel(2)"></span>
                <div class="comm_shell_navs">
                    <div class="item" v-for="(item,index) in resultList" :key="index"
                        :class="{'active':shell_model_item===index}" @click="shell_model_item=index">
                        {{item.name}}
                    </div>
                </div>
                <div class="comm_content_body">
                    <div class="com_content_list" v-for="(item,index) in assetslist" :key="index">
                        <div class="mt20 terminal" :style="{zIndex:shell_model_item==index?10:1}" :id="'terminal'+index"></div>
                    </div>
                </div>
            </div>
        </div>

    </div>
    <script>var require = { paths: { 'vs': 'https://cdn.bootcss.com/monaco-editor/0.16.2/min/vs' } };</script>
    <script src="//cdn.bootcss.com/monaco-editor/0.16.2/min/vs/loader.js"></script>
</div>
<script>
    let editor = null;
    let xteamlist = null;
    let socket = null;
    new Vue({
        el: '#team',
        data: function () {
            return {
                assetslist: [],
                multipleSelection: [],
                sshkey: {
                    dialogSshKeyVisible: false,
                    sshKey: '',
                    email: '',
                    assetsItem: {},
                },
                tasklist:[],
                dialogTableVisible:false,
                taskItem: {},
                type:'',
                resultList:[],
                dialogBuildVisible:false,
                shell_model_item: 0,
                model_icon: 1,
                is_build:false,
            }
        },
        mounted() {
            this.getDatas();
            this.getCommtaskList();
        },
        methods: {
            getCommtaskList() {
                util.ajax({
                    type: 'get',
                    url: `${config.baseApi}api/v1/commtask/list`,
                    success: data => {
                        this.tasklist = data.data || [];
                    }
                })
            },
            getDatas(){
                const asslist = util.getStorage('session','assets_list_configs');
                this.assetslist = asslist ? JSON.parse(asslist) : [];
                setTimeout(() => { this.assetslist.forEach(item => { this.$refs.multipleTable.toggleRowSelection(item, true); }) })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            showSshKey(item) {
                if (this.sshkey.assetsItem._id !== item._id) this.sshkey.sshKey = '';
                this.sshkey.assetsItem = item;
                this.sshkey.dialogSshKeyVisible = true;
            },
            getSshKey(type) {
                util.ajax({
                    url: `${config.baseApi}api/v1/util/getAssetSshKey`,
                    data: {
                        type: type,
                        email: this.sshkey.email,
                        host: this.sshkey.assetsItem.outer_ip,
                        port: this.sshkey.assetsItem.port,
                        username: this.sshkey.assetsItem.user,
                        password: this.sshkey.assetsItem.password,
                    },
                    success: data => {
                        this.sshkey.sshKey = data.data;
                    }
                })
            },
            handleTask(assetsItem,commItem){
                util.ajax({
                    url: `${config.baseApi}api/v1/util/handleShellTasks`,
                    data: {
                        shell_type: commItem.type,
                        shell_body: commItem.shell_body,
                        shell_opction: commItem.shell_opction,
                        shell_path: commItem.shell_path,
                        host: assetsItem.outer_ip,
                        port: assetsItem.port,
                        username: assetsItem.user,
                        password: assetsItem.password,
                    },
                    success: data => {
                        popup.miss({ title: data.data.result })
                    }
                })
            },
            addNewCommTask(){
                location.href="/commtask?model=1"
            },
            showTaskOpctions(type, taskItem, assetsItem) {
                if(type === 1){
                    if(!this.multipleSelection.length){
                        popup.alert({title:'请选择需要执行任务的资产列表'})
                        return
                    } else {
                        this.resultList = this.multipleSelection;
                    }
                }else if(type === 2){
                    this.resultList = [assetsItem]
                }
                this.is_build = false;
                this.type = type;
                this.taskItem = taskItem;
                editor ? editor.setValue(taskItem.shell_body) : setTimeout(() => { this.runMonaco('editor', taskItem.shell_body); });
                this.dialogTableVisible = true;
            },
            runMonaco(id, data) {
                //载入Monaco
                const _this = this;
                require(['vs/editor/editor.main'], function () {
                    //得到支持的语言
                    var modesIds = monaco.languages.getLanguages().map(function (lang) { return lang.id }).sort();
                    //创建编辑器
                    editor = monaco.editor.create(document.getElementById(id), {
                        //内容
                        value: data,
                        //语言
                        language: 'shell',
                        scrollBeyondLastLine: false,
                        automaticLayout: true,
                        //主题，三款：vs、vs-dark、hc-black
                        theme: 'vs-dark',
                        readOnly:true,
                        //代码略缩图
                        minimap: {
                            enabled: true
                        }
                    });
                });
            },
            generateBuildConfig() {
                util.ajax({
                    url: `${config.baseApi}api/v1/build/generateBuildConfig`,
                    data: {
                        taskItem: this.taskItem,
                        assetsList: this.resultList,
                    },
                    success: data => {
                        popup.miss({ title: '操作成功!' })
                    }
                })
            },
            updageAppConfigs(){
                location.href="/commtask?taskId=" + this.taskItem._id
            },
            deployApplications(type){
                if(this.taskItem.type == 1){
                    this.handleTask(this.resultList[0],this.taskItem);
                    return;
                }

                let startType = '';

                if (!xteamlist && !this.is_build) {
                    // 第一次点击发布
                    startType = 'new';
                } else if (this.is_build) {
                    // 第二次点击发布
                    startType = 'agein';
                } else if (!this.is_build && xteamlist) {
                    // 切换了发布方式
                    startType = 'switch';
                }

                // 弹出框
                this.dialogBuildVisible = true;
                this.is_build = true;

                setTimeout(() => {
                    // 开始
                    const result = util.startSocketXteam({
                        taskItem: this.taskItem,
                        buildType: 'buildtasks',
                        assetsList: this.resultList,
                        startType,
                    });
                    socket = result.socket;
                    xteamlist = result.xteamList;
                })
            },
            handleShellModel(type) {
                if (type === 3) {
                    if (this.model_icon === 1) {
                        this.model_icon = 2;
                        type = 3;
                    } else {
                        this.model_icon = 1;
                        type = 4;
                    }
                }
                util.setSocketXteam(type, xteamlist, socket);
            },
        }
    })
</script>